
// ExtJS相关的封装
Ext.ns('KE');
Ext.ns('KE.ux.plugins');
Ext.ns('Ext.ux.Toast');
Ext.ux.Toast.msg = function(title, content) {
	 Ext.toast({
	     html: content,
	     title: title,
	     width: 200,
	     align: 't'
 	});
}

KE.BaseModel = Ext.extend(Ext.data.Model, {
	constructor : function(conf) {
		Ext.apply(this, conf);
		this.callParent(arguments);
	}
});

/**
 * 查找Grid中选中的ids
 */
function $getGdSelectedIds(grid, idName){
	var selRs = grid.getSelectionModel().getSelection();
	var ids = Array();
	for (var i = 0; i < selRs.length; i++) {
		ids.push(eval('selRs[i].data.'+idName));
	}
	return ids;
}

/**

 * 选择grid一行记录，返回选中行的数据

 * */
function $selectOne(grid) {
	var selRs = grid.getSelectionModel().getSelection();
	if(selRs.length != 1) {
		Ext.ux.Toast.msg('操作信息', '请选择且只选一条要操作的记录！');
		return false;
	}
	return selRs[0].data;
}

/**
 * 删除
 * */
function $postDel(conf){
	Ext.Msg.confirm('信息确认', conf.confirmText||'您确认要删除所选记录吗？', function(btn) {
		if (btn == 'yes') {
			Ext.Ajax.request({
				url: conf.url,
				params: {ids : conf.ids},
				method: 'POST',
				success: function(response, options) {
					if(conf.callback){
						conf.callback.call(this);
						return;
					}
					Ext.ux.Toast.msg('操作信息','成功删除该记录！');
					if(conf.grid){
						conf.grid.getStore().reload();
					}
				},
				failure: function(response,options) {
					Ext.ux.Toast.msg('操作信息','操作出错，请联系管理员！');
				}
			});
		}
	});
}
/** 包装Ajax */
function $postAjax(conf) {
	var async = conf.async || true;
	Ext.Ajax.request({
		async: async,
		url: conf.url,
		params: conf.params || {},
		method: 'POST',
		scope: this,
		success: function(response, options) {
			if(conf.callback){
				conf.callback.call(this, Ext.JSON.decode(response.responseText));
				return;
			}
			Ext.ux.Toast.msg('操作信息','操作成功！');
			if(conf.grid){
				conf.grid.getStore().reload();
			}
		},
		failure: function(response,options) {
			Ext.ux.Toast.msg('操作信息','操作出错，请联系管理员！');
		}
	});
}


/**
 * 提交表单
 */
function $postForm(conf){
	if(conf.formPanel.getForm().isValid()){
		var scope = conf.scope ? conf.scope : this;
		conf.formPanel.getForm().submit({
			scope:scope,
			url : conf.url,
			method : 'post',
			params: conf.params,
			waitMsg : '正在提交数据...',
			success : function(fp, action) {
				Ext.ux.Toast.msg('操作信息', '成功信息保存！');
				if(conf.callback){
					conf.callback.call(scope,fp,action);
				}
			},
			failure : function(fp, action) {
				Ext.MessageBox.show({
						title : '操作信息',
						msg : '信息保存出错，请联系管理员！',
						buttons : Ext.MessageBox.OK,
						icon : 'ext-mb-error'
					});
				if(conf.callback){
					conf.callback.call(scope,fp,action);
				}
			}
		});
	}
}

/**
 * 删除Grid选中的记录
 */
function $delGridRs(conf){
	var ids = $getGdSelectedIds(conf.grid, conf.idName);
	if (ids.length == 0) {
		Ext.ux.Toast.msg("操作信息", "请选择要删除的记录！");
		return;
	}
	var params={
		url:conf.url,
		ids:ids,
		grid:conf.grid
	};
	$postDel(params);
}
/**
 * 搜索，把查询的Panel提交，并且更新gridPanel的数据，
 * 使用以下所示：
 * 	$search({
 *		searchPanel:this.searchPanel,
 *		gridPanel:this.gridPanel
 *	});
 */
function $search(conf){
	var searchPanel = conf.searchPanel;
	var gridPanel = conf.gridPanel;
	if (searchPanel.getForm().isValid()) {
		var store = gridPanel.getStore();
		// 使用jquery获得表单中的元素
		var baseParam = $(searchPanel.getEl().dom).find(':input').serialize();
		var deParams = Ext.urlDecode(baseParam);
		store.proxy.extraParams = store.proxy.baseParams || store.proxy.extraParams || {}; 
		Ext.apply(store.proxy.extraParams, deParams);
		// 跳转到第一页
		if(gridPanel.down('pagingtoolbar')) {
			gridPanel.down('pagingtoolbar').moveFirst();
		}
	}
}

/**
 * 搜索Panel
 */
KE.SearchPanel = Ext.extend(Ext.form.Panel, {
	autoHeight : true,
	border : false,
	submitEmptyText: false,
	layout : {
		type : 'hbox',
		align : 'middle'
	},
	defaults : {
		xtype : 'label',
		style : 'margin-left:10px;'
	},
	style : 'padding:6px;background-color: white',
				
	constructor : function(conf) {
		Ext.apply(this, conf);
		this.callParent();
	}
});

// 基于JSON的store：传入fields和url
Ext.define('KE.JsonStore', {
	extend: 'Ext.data.Store',
	xtype: 'kestore',
	constructor: function(conf){
		Ext.apply(this, conf);
		var def = {
			proxy: {
				type : 'ajax',
				url : conf.url,
				extraParams : conf.baseParams || conf.extraParams,
				actionMethods:{
           			create: "POST", read: "POST", update: "POST", destroy: "POST"
     			},
     			reader : {
					type : 'json',
					rootProperty : 'result',
					totalProperty : 'totalCounts'
				}
			}
		}
		this.callParent([def]);
	}
});

Ext.define('KE.TreeGridPanel', {
	extend: 'Ext.tree.Panel',
	xtype: 'ke-treegrid',
	constructor:function(conf){
		var def = KE.initGridConfig(conf);
		this.callParent([def]);
	}
});
/**
 * 表格管理控件，包括高级查询，数据导出，分页，排序等
 * @class HT.GridPanel
 * @extends Ext.grid.GridPanel
 */
Ext.define('KE.GridPanel', {
	extend: 'Ext.grid.Panel',
	xtype: 'kegrid',
	constructor:function(conf){
		var def = KE.initGridConfig(conf);
		this.callParent([def]);
	}
});

/**
 * 根据普通的配置，生成表格所需要的配置
 */
KE.initGridConfig = function(conf){
	if(!conf.store) {
		conf.store = new Ext.data.Store({
			fields : conf.fields,
			remoteSort: true,
			pageSize: conf.pageSize || 25,
			sorters: conf.sorters || [],
			proxy : {
				type : 'ajax',
				url : conf.url,
				extraParams : conf.params || conf.extraParams || conf.baseParams,
				actionMethods:{
           			create: "POST", read: "POST", update: "POST", destroy: "POST"
     			},
				reader : {
					type : 'json',
					rootProperty : 'result',
					totalProperty : 'totalCounts'
				}
			}
		});
		if(conf.groupField) {
			conf.store.setGroupField(conf.groupField);
		}
		if(conf.url){
			conf.store.load();
		}
	}
	//--start grid cell 内容提示展示
	for(var i=0;i<conf.columns.length;i++){
		if(!conf.columns[i].flex) {
			conf.columns[i].flex = 1;
		}
		if(!conf.columns[i].align) {
			conf.columns[i].align = 'center';
		}
		if(!conf.columns[i].renderer && conf.columns[i].xtype!='actioncolumn') {
			conf.columns[i].renderer = function (value,metaData,record,colIndex,store,view) {
				if(value!=null && typeof value!='undefined') {
			    	metaData.tdAttr = 'data-qtip="'+value+'"';
				}
			    return value;        
			}
		}
	}
	//--end 
	if(!conf.selModel) { 
		//去掉复选框：selModel: 'rowmodel'
		conf.selModel = {selType: 'checkboxmodel'};
		// 只允许选中一个：singleSelect: true
		if(conf.singleSelect) {
			conf.selModel.mode = 'single';
		}
	}
	if(conf.columns){
		// 可以配置rownumber
		if(conf.rownum==undefined || conf.rownum==true) {
			var rownumbercfg = conf.rownumbercfg || {width: 35};
			conf.columns.unshift(new Ext.grid.RowNumberer(rownumbercfg));
		}
	}
	if(!conf.tbar && conf.isShowTbar!=false){
		conf.tbar = new Ext.Toolbar();
	}

	conf.plugins = conf.plugins || [];
	//导出[传入exportCfg]
	if(conf.exportable){
		conf.plugins.push(new KE.ux.plugins.Export({store:conf.store, exportCfg: conf.exportCfg}));
	}
	//打印
	if(conf.printable){
		conf.plugins.push(new KE.ux.plugins.Print());
	}
//	if(conf.forceFit!==false) {
//		conf.forceFit = true;	
//	}
	var def = {
				shim : true,
				trackOver : true,
				stripeRows : true,
				columnLines: true,
				viewConfig : {
					enableRowBody : false,
					showPreview : false,
					enableTextSelection : true
				},
				bbar : (conf.showPaging==null || conf.showPaging) ? new KE.PagingBar({store : conf.store}):null
	};
	Ext.apply(def, conf);
	
	return def;
}
KE.PagingBar=Ext.extend(Ext.PagingToolbar,{
	constructor:function(conf){
		var newConf={
			//pageSize : conf.store.proxy.extraParams.limit ? conf.store.proxy.extraParams.limit:25,
			displayInfo : true,
			displayMsg : '显示从{0}至{1}， 共{2}条记录',
			emptyMsg : '当前没有记录',
			plugins: [Ext.create('Ext.ux.PagingToolbarResizer', {
					options : [25, 50, 100, 500],
					displayText: '每页记录数'
				})]
		};
		if(conf.exportable){
			newConf.plugins.push(new HT.ux.plugins.Export({store:conf.store}));
		}
		if(conf.printable){
			newConf.plugins.push(new HT.ux.plugins.Print());
		}
		
		Ext.apply(newConf, conf);
		this.callParent([newConf]);
	}
});

/**
 * 取到某项目的数据字典
 * @class DicCombo
 * @extends Ext.form.ComboBox
 */
Ext.define('DicCombo', {
	extend: 'Ext.form.ComboBox',
	xtype: 'diccombo',
	
	triggerAction : 'all',
	queryMode : 'local',		
	
	constructor:function(config){
		Ext.apply(this, config);
		var isDisplayItemName = this.isDisplayItemName;
		var extraParams = this.extraParams || {};
		extraParams['Q_EQS_itemName'] = this.itemName;
		
		this.store = new Ext.data.ArrayStore({
				autoLoad : true,
				proxy: {
					type : 'ajax',
					extraParams: extraParams,
					url : __ctxPath + '/system/loadItem2Dictionary.do',
					actionMethods:{
               			create: "POST", read: "POST", update: "POST", destroy: "POST"
         			}
				},
				fields : ['itemId', 'itemName']
			});
		
		var def = {
			displayField : 'itemName',
			valueField : isDisplayItemName?'itemName':'itemId'
		}
		this.callParent([def]);
	}
});


/**
 * 在分页栏中的导出插件
 * @class HT.ux.plugins.Export
 * @extends Object
 */
KE.ux.plugins.Export = Ext.extend(Object, {
	constructor: function(config){
    	Ext.apply(this, config);
    	this.callParent([config]);
	},

  	init : function(grid) {
  		//导出字段设置
  		var expBtn = new Ext.Button({
			text : '导出字段设置',
  			iconCls : 'btn-setting',
			listeners: {
				click: function(){
					var gp;
					if(grid.getXType()!='kegrid'){
	  					gp = grid.findParentBy (
	            			function (ct, cmp) {return (ct instanceof Ext.grid.GridPanel) ? true : false;}
	            		);
					}else{
						gp = grid;
					}
					setExportColumn(gp);
				}
			}
	  	});
	  	//导出菜单项可配置
	  	var excelBtn = new Ext.SplitButton({
	  		text:'导出',
	  		iconCls:'btn-archive-copy',
	  		menu: new Ext.menu.Menu({
	  			items:[]
	  		})
	  	});
	  	//通过配置定义execlBtn
	  	if(this.exportCfg) {
	  		if(this.exportCfg.execl != false) {
	  			if(this.exportCfg.expSel) {
	  				excelBtn.menu.add({
		  				text:'导出选中记录Xls',
		  				iconCls:'btn-xls',
		  				listeners: {click: function(){
		  					var gp;
		  					if(grid.getXType()!='kegrid'){
			  					gp = grid.findParentBy (
			            			function (ct, cmp) {;return (ct instanceof Ext.grid.GridPanel) ? true : false;});
		  					}else{
		  						gp = grid;
		  					}
		  					CommonExport(gp,false,'xls', true);
		  				}}
	  				});
	  			}
	  			excelBtn.menu.add({
	  				text:'导出全部记录Xls',
	  				iconCls:'btn-xls',
	  				listeners: {click: function(){
	  					var gp;
	  					if(grid.getXType()!='kegrid'){
		  					gp = grid.findParentBy (
		            			function (ct, cmp) {;return (ct instanceof Ext.grid.GridPanel) ? true : false;});
	  					}else{
	  						gp = grid;
	  					}
	  					CommonExport(gp,true,'xls');
	  				}}
	  			});
	  		}
	  		if(this.exportCfg.pdf) {
	  			if(this.exportCfg.expSel) {
	  				excelBtn.menu.add({
		  				text:'导出选中记录PDF',
		  				iconCls:'btn-pdf',
		  				listeners: {click: function(){
		  					var gp;
		  					if(grid.getXType()!='kegrid'){
			  					gp = grid.findParentBy (
			            			function (ct, cmp) {;return (ct instanceof Ext.grid.GridPanel) ? true : false;});
		  					}else{
		  						gp = grid;
		  					}
		  					CommonExport(gp,false,'pdf', true);
		  				}}
	  				});
	  			}
	  			excelBtn.menu.add({
	  				text:'导出全部记录PDF',
	  				iconCls:'btn-pdf',
	  				listeners: {click: function(){
	  					var gp;
	  					if(grid.getXType()!='kegrid'){
		  					gp = grid.findParentBy (
		            			function (ct, cmp) {;return (ct instanceof Ext.grid.GridPanel) ? true : false;});
	  					}else{
	  						gp = grid;
	  					}
	  					CommonExport(gp,true,'pdf');
	  				}}
	  			});
	  		}
	  	}
	  	
	  	if(grid.getXType()!='kegrid'){
		  	grid.down('toolbar').add('->');
		  	grid.down('toolbar').add('-');
		  	grid.down('toolbar').add(expBtn);
		  	grid.down('toolbar').add(excelBtn);
		  	grid.down('toolbar').add('-');
		  	
		  	grid.on({
		      beforedestroy: function(){
		        excelBtn.destroy();
		      }
		    });
	  	}else{
	  		grid.down('toolbar').add(expBtn);
	  		grid.down('toolbar').add(excelBtn);
	  	}
	  }
});

// 导出字段设置
function setExportColumn(gridObj) {
	// 创建一个Window来设置
	var win = Ext.create('Ext.ux.ExportColumnSettingWin', {
		grid: gridObj,
		cid: 'id_'+new Date().getTime()
	});
	win.show();
}

/**
 * 导出公共方法，在本页下载，不打开另一页
 * param: gridObj 取得grid
 * 		  isExportAll 是否导出所有
 * 		  exportType 导出的类型
 */
function CommonExport(gridObj,isExportAll,exportType, isSel){
	var cols = gridObj.columns;
	var colName = '';
	var colId = '';
	for(var index=0;index<cols.length;index++){
		//标注isExp=false的字段不导出
		if(cols[index].isExp!=false) {
			if(cols[index].dataIndex && cols[index].hideable!=false){
				colName += cols[index].text + ',';
				if(cols[index].javaRenderer != null){
					colId += "javaRenderer"+cols[index].javaRenderer+",";
				} else if(cols[index].javaMethod != null){
					colId += "javaMethod"+cols[index].javaMethod+",";
				} else{
					colId += cols[index].dataIndex + ',';
				}
			}
		}
	}
	
	if(colName.length>0){
		colName = colName.substring(0,colName.length-1);
		colId = colId.substring(0,colId.length-1);
	}
	var parasArr = {
		isExport: true,
		isExportAll: isExportAll,
		exportType: exportType,
		colId: colId,
		colName: colName
	};
	
	Ext.apply(parasArr, gridObj.store.proxy.extraParams);
	
	var elemIF=document.getElementById('downloadFrame');
	if(!elemIF){
		elemIF= document.createElement("iframe");
		elemIF.setAttribute('id','downloadFrame');
		elemIF.hidden=true;
		document.body.appendChild(elemIF);
	}
	
	var ifrdoc;
	if(elemIF.contentDocument){
    	ifrdoc = elemIF.contentDocument;
	}else if(elemIF.contentWindow){
		ifrdoc = elemIF.contentWindow.document;
	}else{
		ifrdoc = elemIF.document;
	}
	
	if(ifrdoc.document){
		ifrdoc=ifrdoc.document;
	}
	var body=ifrdoc.body;
	if(!body){
		ifrdoc.write("<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'></head>");
		body=ifrdoc.createElement('body');
		ifrdoc.appendChild(body);
	}
	
	var elemForm = ifrdoc.getElementById('downloadForm');
	
	//if exist then remove
	if(elemForm){
		ifrdoc.body.removeChild(elemForm);
	}
	
	//create new form and add new parameters
	elemForm=ifrdoc.createElement("form");
	elemForm.id='downloadForm';
	
	ifrdoc.body.appendChild(elemForm);
	
	var url=gridObj.store.proxy.url;
	
	//如果参数传入exportUrl的话，执行此url处理
	if(isSel && gridObj.exportCfg && gridObj.exportCfg.selUrl) {
		//获得选中id
		var ids = $getGdSelectedIds(gridObj, gridObj.exportCfg.selId||'id');
		if(ids == '') {
			Ext.ux.Toast.msg('操作信息','至少选择一条记录来导出！');
			return ;
		}
		Ext.apply(parasArr, {sids: ids});
		url = gridObj.exportCfg.selUrl;
	}
	
	for(var v in parasArr){
		var elmObj = ifrdoc.createElement("input");
		elmObj.type = "hidden";
    	elmObj.name = v;
    	elmObj.value = parasArr[v];
		elemForm.appendChild(elmObj);
	}
	elemForm.method = 'post';
	elemForm.action = url;
	elemForm.submit();
};

/**
 * 打印plugin
 * @class HT.ux.plugins.Print
 * @extends Object
 */
KE.ux.plugins.Print = Ext.extend(Object, {
  	constructor: function(config){
    	Ext.apply(this, config);
    	HT.ux.plugins.Print.superclass.constructor.call(this, config);
  	},

  	init : function(grid) {
	  	var printBtn = new Ext.Button({
	  		text:'打印',
	  		iconCls:'btn-print',
	  		listeners: {click: function(){
	  			if(grid.getXType()!='kegrid'){
					var gp = grid.findParentBy (
		    		function (ct, cmp) {;return (ct instanceof Ext.grid.GridPanel) ? true : false;});
		    		gpObj = document.getElementById(gp.id);
	  			}else{
	  				gpObj = document.getElementById(grid.id);
	  			}
	  			window.open(__ctxPath+'/js/printer/Print.jsp');
			}}
	  	});
  	
	  	if(grid.getXType()!='kegrid'){
		  	grid.down('toolbar').add('->');
		  	grid.down('toolbar').add('-');
		  	grid.down('toolbar').add(printBtn);
		  	
		  	grid.on({
		      	beforedestroy: function(){
		        	printBtn.destroy();
		      	}
		    });
	  	}else{
	  		grid.down('toolbar').add(printBtn);
	  	}
  }
});

KE.FormPanel=Ext.extend(Ext.form.Panel,{
	constructor:function(conf){
		var def = {
					layout : 'form',
					bodyStyle:'padding:5px',
					defaults : {
						anchor : '96%,96%'
					},
					defaultType : 'textfield',
					border:false
			};
		Ext.apply(def,conf);
		this.callParent([def]);
	}
});

/*
 * 为Form表单设置加载数据,使用方式如下：
 * this.formPanel.loadData({
 *		url:__ctxPath + '/system/getAppRole.do?roleId=' + this.roleId,
 *		preName:'AppRole',
 *		root:'data'
 *	});
 */
Ext.override(Ext.Panel, {
	loadData : function(conf){
		if(!conf.root){
			conf.root='data';
		}
		var ct = this;
		//遍历该表单下所有的子项控件，并且为它赋值	
		var setByName=function(container, data){
			var items=container.items;
			if(items!=null&&items!=undefined&&items.getCount){
				for(var i=0;i<items.getCount();i++){
					var comp=items.get(i);
					//判断组件的类型，并且根据组件的名称进行json数据的自动匹配
					var xtype=comp.getXType();
					// 像htmleditor一类元素，不能再判断它的items了
					if(xtype!='htmleditor' && comp.items) {
						setByName(comp,data);
						continue;
					}
					try{
						if(xtype=='textfield' || xtype=='textareafield'  || xtype=='radiofield' 
							|| xtype=='datefield' || xtype=='combobox'   || xtype=='hiddenfield' 
							|| xtype=='hidden'    || xtype=='textarea'   || xtype=='combo'
							|| xtype=='htmleditor'||xtype=='displayfield'|| xtype=='diccombo' 
							|| xtype=='ckeditor'  ||xtype=='numberfield' || xtype=='checkboxfield') {
								
							var name=comp.getName();
							if(name){
								if(conf.preName){
									if(name.indexOf(conf.preName)!=-1){
										name=name.substring(conf.preName.length+1);
									}
								}
								var val=eval(conf.root+'.'+name);
								if(xtype=='textarea') {
									val = val.replaceAll('<br>', '\n');
								}
								if(val!=null && val!=undefined){
									comp.setValue(val);
								}
							}
						}
					} catch(e){
						// alert(e);
					}
				}
			}
		};
		var scope=conf.scope?conf.scope:ct;
		var params=conf.params?conf.params:{};
		Ext.Ajax.request({
			method:'POST',
			url:conf.url,
			scope:scope,
			params:params,
			success:function(response,options){
				var json=Ext.util.JSON.decode(response.responseText);
				var data=null;
				if(conf.root){
					data=eval('json.'+conf.root);
				}else{
					data=json;
				}
				if(data == null) return;
				
				setByName(ct,data);	
				if(conf.success){
				    conf.success.call(scope, data, response, options);
				}
			},//end of success
			failure:function(response,options){
				if(conf.failure){
				    conf.failure.call(scope,response,options);
				}
			}
		});
	}
});

Ext.override(Ext.container.Container, {
	getCmpByName : function(name) {
		if(this.xtype=='form') {
			// 无法查找到hiddenName, 应该使用name
			var cmp = this.getForm().findField(name);
			if(cmp) return cmp;
		}
		var getByName = function(container, name) {
			var items = container.items;
			if (items && items.getCount!=undefined) {
				for (var i = 0; i < items.getCount(); i++) {
					var comp = items.get(i);
					if (name==comp.name || name==comp.hiddenName) {
						return comp;
						break;
					}
					var cp = getByName(comp, name);
					if (cp != null) return cp;
				}
			}
			return null;
		};
		return getByName(this, name);
	},
	initComponent : function() {
		if (this.allowBlank !== undefined && !this.allowBlank) {
			if (this.fieldLabel) {
				this.fieldLabel += '<font color=red>*</font>';  
			}
		}
		this.callParent(arguments);
	}
});

//为form表单中必填项添加红色*号标志 
Ext.override(Ext.form.field.Base, {// 针对form中的基本组件
	initComponent : function() {
		if (this.allowBlank !== undefined && !this.allowBlank) {
			if (this.fieldLabel) {
				this.fieldLabel += '<font color=red>*</font>';  
			}
		}
		this.callParent(arguments);
	}
});


/**
 * 附件下载
 * */
Ext.define('KE.AttachPanel', {
		extend: 'Ext.form.FieldContainer',
		xtype: 'attachpanel',
		constructor : function(conf) {
			Ext.applyIf(this, conf);
			this.initUI();
			var def = {
						layout : {
							type: 'hbox',
							margin : '5 5 5 0',
							align : 'top'
						},
						border : false,
						width : '100%',
						autoHeight : true,
						minHeight: 100,
						defaults : {
							margin : '0 5 0 0'
						},
						items : [
							/*{
								xtype : 'label',
								text : conf.fieldLabel || '附件:',
								width : conf.width || 100
							}, */this.attachPanel, {
							xtype : 'button',
							iconCls : 'menu-attachment',
							scope : this,
							handler : this.addFile,
							text : '添加'
						}, {
							xtype : 'button',
							iconCls : 'reset',
							scope : this,
							text : '清除所选',
							handler : this.clearSelectedFiles
//						}, {
//							xtype : 'button',
//							iconCls : 'btn-cancel',
//							scope : this,
//							handler : this.clearFile,
//							text : '清除所有'
						}]
					};
			this.callParent([def]);
		},
		initUI : function() {
			var me = this;
			this.attachPanel = new KE.GridPanel({
						store : new Ext.data.JsonStore({
							proxy: {
								type: 'ajax',
								url : __ctxPath + '/system/loadByIdsFileAttach.do',
								reader: {
									rootProperty : 'fileAttachs'
								}
							},
							fields : ['fileId', 'fileName']
						}),
						height : this.height || 120,
						scrollable: true,
						showPaging : false,
						isShowTbar : false,
						width : this.gridWidth ? this.gridWidth : 400,
						//hideHeaders : true,
						columns: [{
				            header: 'fileId',
				            hidden : true,
				            dataIndex: 'fileId'
				        },{
				        	header : '文件名',
				        	dataIndex : 'fileName',
				        	renderer : function(value, metadata, record){
				        		return '<a href="'+__ctxPath + '/file-download?fileId='+record.data.fileId+'", target="_blank">'+value+'</a>'
				        	}
				        }, {
				        	text: '管理',
				        	width : 30,
				        	xtype:'actioncolumn',
				        	items: [{
					                iconCls: 'btn-del',
					                tooltip: '删除',
					                scope : this,
					                handler: this.deleteRs
					            }]
				        }]
					});
				this.attachPanel.addListener('rowdblclick', this.rowClick);
		},
		// 添加附件
		addFile : function() {
			var panel = this.attachPanel;
			var outerpanel = this;
			var scope = this.scope ? this.scope : this;
			var dialog = App.createUploadDialog2({
						file_cat : this.fileCat ? this.fileCat : '',
						scope : this.scope ? this.scope : this,
						is_history : true,
						callback : function(data) {
							var store = panel.getStore();
							for (var i = 0; i < data.length; i++) {
									var p = panel.getStore().getModel().create({
										fileId: data[i].fileId,
										fileName: data[i].fileName 
									});
									p.commit();
									store.insert(store.getCount(), p);
									
							}
							panel.getView().refresh();
							outerpanel.doLayout();
						}
					});
			dialog.show();
		},
		/**
		 * 清除附件
		 */
		clearFile : function() {
			this.attachPanel.getStore().removeAll();
			this.attachPanel.getView().refresh();
			this.fileIds = [];
			this.fileNames = [];
			this.doLayout();
		},
		//清除所选
		clearSelectedFiles : function() {
			var store = this.attachPanel.getStore();
			var selRs = this.attachPanel.getSelectionModel().getSelection();
			for (var i = 0; i < selRs.length; i++) {
				store.remove(selRs[i]);
			}
			this.attachPanel.getView().refresh();
			this.doLayout();
		},
		// GridPanel行点击处理事件
		rowClick : function(grid, record) {
			FileAttachDetail.show(record.data.fileId);
		},
		// 删除事件
		removeRs : function(record){
			var store = this.attachPanel.getStore();
			store.remove(record);
			this.attachPanel.getView().refresh();
			this.doLayout();
		},
		// 行的Action
		deleteRs : function(grid, rowIndex, colIndex) {
			var record = grid.getStore().getAt(rowIndex);
			this.removeRs.call(this, record);
					
		},
		getFileIds : function(){
			var store = this.attachPanel.getStore();
			var fileIds = '';
			for(var i=0;i<store.getCount();i++){
				var record = store.getAt(i);
				fileIds += record.get('fileId')+',';
			}
			return fileIds;
		},
		getFileNames : function(){
			var store = this.attachPanel.getStore();
			var fileNames = '';
			for(var i=0;i<store.getCount();i++){
				var record = store.getAt(i); 
				fileNames += record.get('fileName')+',';
			} 
			return fileNames;
		},
		getAttachStore : function(){
			return this.attachPanel.getStore();
		},
		loadByResults : function(results){
			this.attachPanel.getStore().loadData(results);
			this.attachPanel.getView().refresh();
			this.doLayout();
		},
		loadByIds : function(ids){
			this.attachPanel.getStore().load({
					params : {
						ids : ids
					},
					callback:function(){
						this.doLayout();
					},
					scope:this
				}
			);
		}
	});


/*
 * 文件附件详细
 */
Ext.ns('FileAttachDetail');
FileAttachDetail.show = function(fileId) {
	var window = new Ext.Window( {
		title : '附件详细信息',
		iconCls : 'menu-attachment',
		width : 480,
		height : 253,
		minHeight : 253,
		modal : true,
		layout : 'form',
		buttonAlign : 'center',
		autoLoad : {
			url : __ctxPath + '/fileDetail.do?fileId=' + fileId
		},
		buttons : [ {
			xtype : 'button',
			iconCls : 'btn-close',
			text : '关闭',
			handler : function() {
				window.close();
			}
		} ]
	});
	window.show();
};

Ext.define('KE.HBoxPanel', {
	extend: 'Ext.Panel',
	constructor:function(conf){
		var newConf={
			border:false,
            defaults:{margins:'0 5 0 0'},
			layout:{
				type: 'hbox',
				padding:'5',
                pack:'center',
                align:'middle'
			}
		};
		Ext.apply(newConf,conf);
		this.callParent([newConf]);
	}
});

// 构建客户端分页的GridPanel
function $makeLocalGridPanel(conf) {
	var gridPanel;
	if(conf.forceFit!==false) {
		conf.forceFit = true;	
	}
	//--start grid cell 内容提示展示
	for(var i=0;i<conf.columns.length;i++){
		if(!conf.columns[i].renderer && conf.columns[i].xtype!='actioncolumn') {
			conf.columns[i].renderer = function (value,metaData,record,colIndex,store,view) {
				if(value!=null && typeof value!='undefined') {
			    	metaData.tdAttr = 'data-qtip="'+value+'"';
				}
			    return value;        
			}
		}
	} //--end 
	if(!conf.selModel) { 
		//去掉复选框：selModel: 'rowmodel'
		conf.selModel = {selType: 'checkboxmodel'};
		// 只允许选中一个：singleSelect: true
		if(conf.singleSelect) {
			conf.selModel.mode = 'single';
		}
	}
	if(conf.columns){
		// 可以配置rownumber
		var rownumbercfg = conf.rownumbercfg || {width: 35};
		conf.columns.unshift(new Ext.grid.RowNumberer(rownumbercfg));
	}
	if(!conf.tbar && conf.isShowTbar!=false){
		conf.tbar = new Ext.Toolbar();
	}
	
	// 通过同步的AJAX请求获得全部数据
	$postAjax({
		async : false, // 同步
		url: conf.url,
		callback : function(data) {
			conf.store = new Ext.data.Store({
				fields : conf.fields,
				data : data,
				pageSize : conf.pageSize || 25,
				proxy : {
					type : 'memory',
					enablePaging : true,
					reader : {
						type : 'json',
						rootProperty : 'result'
					}
				}
			}); // end store
			var def = {
				shim : true,
				trackOver : true,
				stripeRows : true,
				viewConfig : {
					enableRowBody : false,
					showPreview : false,
					enableTextSelection : true
				},
				bbar : (conf.showPaging==null || conf.showPaging) ? new KE.PagingBar({store : conf.store}):null
			};
			Ext.apply(def, conf);
			gridPanel = Ext.create('Ext.grid.Panel', def);
			// 解决分页条初始只有1页的问题
			Ext.defer(function() {
						gridPanel.getStore().reload();
					}, 50);
		}
	});
	return gridPanel;
}
// 端户端分页Grid的查询：
function $search2(conf){
	var searchPanel = conf.searchPanel;
	var gridPanel = conf.gridPanel;
	if (searchPanel.getForm().isValid()) {
		// 使用jquery获得表单中的元素
		var baseParam = $(searchPanel.getEl().dom).find(':input').serialize();
		var deParams = Ext.urlDecode(baseParam);
		$postAjax({
			url: conf.url,
			params: deParams,
			callback : function(data) {		
				var fields = gridPanel.fields;
				var pageSize = gridPanel.getStore().pageSize;
				var store = new Ext.data.Store({
					fields : fields,
					data : data,
					pageSize : pageSize,
					proxy : {
						type : 'memory',
						enablePaging : true,
						reader : {
							type : 'json',
							rootProperty : 'result'
						}
					}
				});
				gridPanel.setStore(store);
				
				var tbar = gridPanel.down('pagingtoolbar');
				if(tbar) {
					tbar.setStore(store);
					// 重新加载插件：PagingToolbarResizer
					tbar.plugins[0].bind(tbar);
				}
			}			
		});		
	}
}

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
	if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
		return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")),
				replaceWith);
	} else {
		return this.replace(reallyDo, replaceWith);
	}
}
